package com.example.campus_order_sb.controller;

import com.example.campus_order_sb.dto.CategoryRequest;
import com.example.campus_order_sb.entity.Category;
import com.example.campus_order_sb.entity.User;
import com.example.campus_order_sb.enums.UserType;
import com.example.campus_order_sb.repository.UserRepository;
import com.example.campus_order_sb.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/categories")
@CrossOrigin
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<?> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return ResponseEntity.ok(categories);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "获取分类失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getCategoryById(@PathVariable Integer id) {
        try {
            Category category = categoryService.getCategoryById(id);
            return ResponseEntity.ok(category);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "获取分类失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    @PostMapping
    public ResponseEntity<?> createCategory(@RequestBody CategoryRequest categoryRequest, @RequestParam Integer userId) {
        try {
            // 验证用户权限
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 只有商家可以添加分类
            if (userType != UserType.MERCHANT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            Category createdCategory = categoryService.createCategory(categoryRequest);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdCategory);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "创建分类失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateCategory(
            @PathVariable Integer id,
            @RequestBody CategoryRequest categoryRequest,
            @RequestParam Integer userId) {
        try {
            // 验证用户权限
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 只有商家可以更新分类
            if (userType != UserType.MERCHANT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            Category updatedCategory = categoryService.updateCategory(id, categoryRequest);
            return ResponseEntity.ok(updatedCategory);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "更新分类失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCategory(@PathVariable Integer id, @RequestParam Integer userId) {
        try {
            // 验证用户权限
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 只有商家可以删除分类
            if (userType != UserType.MERCHANT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            categoryService.deleteCategory(id);

            Map<String, String> response = new HashMap<>();
            response.put("message", "分类删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "删除分类失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
}
